package com.zlzlib.liblistview.filter;

import android.text.TextUtils;
import android.widget.Filter;

import com.zlzlib.liblistview.adapter.BaseNormalAdapter;

import java.util.ArrayList;
import java.util.List;


/**
 * @Desc: 总数据确定的列表筛选过滤器
 * @Copyright:
 * @DateTime: 2022/8/5 10:17
 * @Author zlz
 * @Version 1.0
 */
public class BaseAdapterFilter<T extends BaseFilterFace> extends Filter {

    private final BaseNormalAdapter<T> adapter;
    private final List<T> dataAll = new ArrayList<>();
    private final FilterResults results = new FilterResults();

    public BaseAdapterFilter(BaseNormalAdapter<T> adapter) {
        this.adapter = adapter;
        dataAll.addAll(adapter.getData());
    }

    public void refreshAllData(List<T> list) {
        dataAll.clear();
        dataAll.addAll(list);
    }

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        results.values = dataAll;
        results.count = dataAll.size();
        if (TextUtils.isEmpty(constraint)) {
            return results;
        }
        List<T> con = new ArrayList<>();
        for (T t : dataAll) {
            if (t.isContains(constraint)) {
                con.add(t);
            }
        }
        results.values = con;
        results.count = con.size();
        // 数据匹配
        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        List<T> values = (List<T>) results.values;
        adapter.refreshData(values);
    }

}
